package model.readers.PMetro;

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipResources {

	public boolean debugOn = false;
	String ArhivName;

	private Hashtable htSizes = new Hashtable();
	private Hashtable htJarContents = new Hashtable();

	public ZipResources(String ArhivName) {
		this.ArhivName = ArhivName;
		init();
	}

	public byte[] getResource(String name) {
		return (byte[]) htJarContents.get(name);
	}

	private void init() {
		try {
			ZipFile zf = new ZipFile(ArhivName);
			Enumeration e = zf.entries();
			while (e.hasMoreElements()) {
				ZipEntry ze = (ZipEntry) e.nextElement();
				if (debugOn) {
					System.out.println(dumpZipEntry(ze));
				}
				htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
			}
			zf.close();

			FileInputStream fis = new FileInputStream(ArhivName);
			BufferedInputStream bis = new BufferedInputStream(fis);
			ZipInputStream zis = new ZipInputStream(bis);
			ZipEntry ze = null;
			while ((ze = zis.getNextEntry()) != null) {
				if (ze.isDirectory()) {
					continue;
				}
				if (debugOn) {
					System.out.println("ze.getName()=" + ze.getName() + ","
							+ "getSize()=" + ze.getSize());
				}
				int size = (int) ze.getSize();
				if (size == -1) {
					size = ((Integer) htSizes.get(ze.getName())).intValue();
				}
				byte[] b = new byte[(int) size];
				int rb = 0;
				int chunk = 0;
				while (((int) size - rb) > 0) {
					chunk = zis.read(b, rb, (int) size - rb);
					if (chunk == -1) {
						break;
					}
					rb += chunk;
				}
				htJarContents.put(ze.getName(), b);
				if (debugOn) {
					System.out.println(ze.getName() + "  rb=" + rb + ",size="
							+ size + ",csize=" + ze.getCompressedSize());
				}
			}
		} catch (NullPointerException e) {
			System.out.println("done.");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String dumpZipEntry(ZipEntry ze) {
		StringBuffer sb = new StringBuffer();
		if (ze.isDirectory()) {
			sb.append("directory  ");
		} else {
			sb.append("file  ");
		}
		if (ze.getMethod() == ZipEntry.STORED) {
			sb.append("stored   ");
		} else {
			sb.append("defalted ");
		}
		sb.append(ze.getName());
		sb.append("\t");
		sb.append("" + ze.getSize());
		if (ze.getMethod() == ZipEntry.DEFLATED) {
			sb.append("/" + ze.getCompressedSize());
		}
		return (sb.toString());
	}
}